// 资产总览
import type { AssetOverviewState, NumberStatisticItem } from './typings'
import { defineComponent, ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElCard, ElRow, ElCol, ElLink, ElIcon, ElImage } from 'element-plus'
import { Remove } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { cloneDeep } from 'lodash'
import useVuexGetters from '~/hooks/useVuexGetters'
// import AliIcon from '~/components/AliIocn' // 阿里巴巴图标库
import ChartsStastic from '~/pages/assetOverview/components/ChartsStastic' // 工区总设施投入占比图
import NumberStatisticOption from './option'
import plusImg from '~/assets/plus.png'
import { EL_SPACE_SIZE_SECOND_GEAR, SPAN_STYLE_SIX } from '~/utils/const'
import styles from './index.module.scss'

export default defineComponent(function AssetOverview() {
  const store = useStore()
  const numberStatisticDatas = ref<AssetOverviewState['numberStatistic']>()
  // const numPerRow = ref() // 一行显示个数
  const state = reactive<AssetOverviewState>({
    expandNumberStatisticOne: false, // 是否展开
    showExpandNumberStatistic: false,
    numberStatistic: []
  })
  const userInfo = JSON.parse(localStorage.getItem('saber-userInfo')!) // 获取当前登录人

  const assetOverviewVuexState = useVuexGetters('assetOverview', ['getImage'])

  onMounted(() => {
    ifUpdateCache() // 是否更新缓存
    // getNumPerRow() // 一行显示个数
    window.addEventListener('resize', handleWindowResize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleWindowResize)
  })

  // 监听窗口变化和数据多少 选择是否展示展开按钮
  function handleWindowResize() {
    if (window.innerWidth < 1200 && state.numberStatistic?.length < SPAN_STYLE_SIX.xl) {
      state.showExpandNumberStatistic = false
    } else if (window.innerWidth >= 1200 && state.numberStatistic?.length < SPAN_STYLE_SIX.lg) {
      state.showExpandNumberStatistic = false
    } else {
      state.showExpandNumberStatistic = true
    }
  }

  // 是否更新缓存
  const ifUpdateCache = async () => {
    const res = await store.dispatch('assetOverview/GetAssetModelList')
    if (res?.code === 200) {
      let ifUpdate = false // 是否更新缓存
      const info = JSON.parse(
        localStorage.getItem(`assetOverviewNumberInfo${userInfo.content.userId}`)!
      ) // 所有缓存
      if (!info || (info && info.length !== res.data.length)) {
        getNumberStatisticDatas(!ifUpdate) // 更新数量统计的显示
      } else if (info && info.length === res.data.length) {
        const infoCode = info.map((item: { code: string }) => item.code) // 已缓存的code
        const newCode = res.data.map((item: { code: string }) => item.code) // 当前接口最新code
        // 比较两者内容是否一致, 顺序不计
        for (let i = 0; i < infoCode.length; i++) {
          if (newCode.indexOf(infoCode[i]) === -1) {
            ifUpdate = true
            break
          }
        }
        getNumberStatisticDatas(ifUpdate) // 即使有缓存也更新数量统计
      }
    }
  }

  // 一行显示个数
  // const getNumPerRow = () => {
  //   const numberStatisticCard = document.getElementById('numberStatisticCard')?.clientWidth ?? 0 // 卡片宽
  //   const numberStatisticExpand = document.getElementById('numberStatisticExpand')?.offsetWidth ?? 0 // 展开宽
  //   // 一行显示几个
  //   numPerRow.value = Math.trunc(numberStatisticExpand / numberStatisticCard) - 1 // 20是卡片margin右边距
  // }

  // 获取数量统计数据 默认显示 配电设施、灯源、回路、灯杆
  const getNumberStatisticDatas = async (ifUpdate: boolean) => {
    const res = await store.dispatch('assetOverview/GetAssetModelList')
    let modelCodes = '' // 用于查数量数据的code
    if (res?.code === 200) {
      const info = JSON.parse(
        localStorage.getItem(`assetOverviewNumberInfo${userInfo.content.userId}`)!
      ) // 所有缓存
      const orderInfo = JSON.parse(
        localStorage.getItem(`assetOverviewNumberOrder${userInfo.content.userId}`)!
      ) // 上次缓存显示的数据

      numberStatisticDatas.value = [] // 显示的全部数据
      if (info && !ifUpdate) {
        // 非初次缓存 获取原来的值
        numberStatisticDatas.value = orderInfo
        orderInfo.map((item: NumberStatisticItem) => (modelCodes += `,${item.code}`))
      } else {
        // 初次缓存
        modelCodes = 'Distribution,LampBase,DistributionLoop,LampPost'
        let numberStatisticInfo = [] // 所有数据
        for (let i = 0; i < res.data.length; i++) {
          const item = res.data[i]
          // 单位
          let unit = ''
          if (item.code === 'DistributionLoop') {
            unit = '条' // 回路
          } else if (item.code === 'LampPost') {
            unit = '根' // 灯杆
          } else {
            unit = '个' // 其它
          }

          // 是否显示 默认显示 配电设施、灯源、回路、灯杆
          let show = false
          if (
            item.code === 'Distribution' ||
            item.code === 'LampBase' ||
            item.code === 'DistributionLoop' ||
            item.code === 'LampPost'
          ) {
            show = true
          }
          numberStatisticInfo!.push({
            code: item.code,
            show,
            name: item.name,
            unit
          })

          // 取显示的全部数据
          if (show) {
            numberStatisticDatas.value!.push({
              code: item.code,
              name: item.name,
              unit
            })
          }
        }

        // 从vuex获取数量统计的图标及背景图
        store.dispatch('assetOverview/GetIconAndBackgroundImage', numberStatisticInfo)
        numberStatisticInfo = cloneDeep(assetOverviewVuexState.getImage.value)
        store.dispatch('assetOverview/GetIconAndBackgroundImage', numberStatisticDatas.value)
        numberStatisticDatas.value = cloneDeep(assetOverviewVuexState.getImage.value)

        // 存所有数据
        window.localStorage.setItem(
          `assetOverviewNumberInfo${userInfo.content.userId}`,
          JSON.stringify(numberStatisticInfo)
        ) // 卡片显隐 做本地浏览器缓存

        // 存所有上次显示顺序
        window.localStorage.setItem(
          `assetOverviewNumberOrder${userInfo.content.userId}`,
          JSON.stringify(numberStatisticDatas.value)
        ) // 卡片显隐 做本地浏览器缓存
      }

      // 数量渲染
      const result = await store.dispatch('assetOverview/GetAssetModelReport', { modelCodes })
      if (result.code === 200) {
        for (let i = 0; i < result.data.length; i++) {
          for (let j = 0; j < numberStatisticDatas.value!.length; j++) {
            if (result.data[i].code === numberStatisticDatas.value![j].code) {
              numberStatisticDatas.value![j].num = result.data[i].num
              break
            }
          }
        }
      }

      // state.showExpandNumberStatistic = true
      state.numberStatistic = numberStatisticDatas.value!
      handleWindowResize()
    }
  }

  // 展开收起
  const handelExpandNumberStatisticVisible = () => {
    state.expandNumberStatisticOne = !state.expandNumberStatisticOne
  }

  // 隐藏卡片
  const handelHiddenCards = (record: NumberStatisticItem) => {
    const info = JSON.parse(
      localStorage.getItem(`assetOverviewNumberInfo${userInfo.content.userId}`)!
    )
    const orderInfo = JSON.parse(
      localStorage.getItem(`assetOverviewNumberOrder${userInfo.content.userId}`)!
    ) // 上次缓存显示的数据
    // 更新所有数据
    for (let i = 0; i < info.length; i++) {
      const item = info[i]
      if (item.code === record.code) {
        item.show = !item.show
        break
      }
    }
    window.localStorage.setItem(
      `assetOverviewNumberInfo${userInfo.content.userId}`,
      JSON.stringify(info)
    ) // 卡片显隐 做本地浏览器缓存

    // 从上次显示顺序数据中 删这次点的隐藏 并存下来
    const updateOrderInfo = []
    for (let i = 0; i < orderInfo.length; i++) {
      const element = orderInfo[i]
      if (element.code !== record.code) {
        updateOrderInfo.push(element)
      }
    }
    window.localStorage.setItem(
      `assetOverviewNumberOrder${userInfo.content.userId}`,
      JSON.stringify(updateOrderInfo)
    ) // 卡片显隐 做本地浏览器缓存
    getNumberStatisticDatas(false)
  }

  // 数量统计 弹窗
  const handelNumberStatisticOption = () => {
    state.showNumberStatisticOption = !state.showNumberStatisticOption
  }

  return () => {
    return (
      <>
        {/* 数量统计 */}
        <ElRow
          class={{
            [styles['number-statistic-box']]: true,
            [styles['shrink-number-statistic']]: !state.expandNumberStatisticOne
          }}
          gutter={EL_SPACE_SIZE_SECOND_GEAR}
        >
          {state.numberStatistic!.map((item) => (
            <ElCol {...SPAN_STYLE_SIX} class={styles['number-statistic']}>
              <ElCard
                shadow="hover"
                class={styles['number-statistic-cards']}
                style={`background-image: ${item.backgroundImage};`}
              >
                <ElRow>
                  <ElCol span={17} class={styles['number-statistic-cards-words']}>
                    <div class={styles['number-statistic-cards-data']}>
                      <ElLink underline={false} class={styles['number-statistic-cards-num']}>
                        {item.num}
                      </ElLink>
                      &nbsp;
                      <span class={styles['number-statistic-cards-unit']}>{item.unit}</span>
                    </div>
                    <span class={styles['number-statistic-cards-name']}>{item.name}</span>
                  </ElCol>
                  <ElCol span={7}>
                    <div class={styles['number-statistic-cards-icon']}>
                      {/* <AliIcon type={item.icon!} /> // icon暂用切图, 阿里图标库上传好了再换这句 */}
                      <ElImage src={item.iconImage!} />
                    </div>
                  </ElCol>
                </ElRow>
                {/* 隐藏 */}
                <span
                  class={styles['number-statistic-cards-hidden']}
                  onClick={() => handelHiddenCards(item)}
                >
                  <ElIcon>
                    <Remove />
                  </ElIcon>
                </span>
              </ElCard>
            </ElCol>
          ))}
          <ElCol {...SPAN_STYLE_SIX} class={styles['number-statistic']}>
            <ElCard shadow="hover" class={styles['number-statistic-cards-add']}>
              <div
                class={styles['number-statistic-cards-add-icon']}
                onClick={handelNumberStatisticOption}
              >
                <ElImage src={plusImg} />
                {/* <AliIcon type="icon-tupianshangchuan" /> */}
              </div>
            </ElCard>
          </ElCol>
        </ElRow>
        {/* 展开图标 */}
        <div
          id="numberStatisticExpand"
          class={{
            [styles['number-statistic-expand-icon']]: state.showExpandNumberStatistic,
            [styles['number-statistic-expand-icon-hid']]: !state.showExpandNumberStatistic
          }}
        >
          {state.showExpandNumberStatistic && (
            <ElLink type="info" underline={false} onClick={handelExpandNumberStatisticVisible}>
              {state.expandNumberStatisticOne ? (
                // <AliIcon type="icon-xiala" /> // icon暂用切图, 阿里图标库上传好了再换这句
                <ElImage src={'/assetOverview/temporaryIconImage/packUp.png'} />
              ) : (
                // <AliIcon type="icon-shouqi" /> // icon暂用切图, 阿里图标库上传好了再换这句
                <ElImage src={'/assetOverview/temporaryIconImage/expand.png'} />
              )}
            </ElLink>
          )}
        </div>

        {/* 数量统计 弹窗 */}
        {state.showNumberStatisticOption && (
          <NumberStatisticOption
            visible={state.showNumberStatisticOption}
            onCancel={handelNumberStatisticOption}
            onGetNumberStatisticDatas={(value) => getNumberStatisticDatas(value)}
          />
        )}

        {/* 图表统计 */}
        <ChartsStastic />
      </>
    )
  }
})
